package kr.hkit.androidcomplete03.ch28;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;

import kr.hkit.androidcomplete03.R;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;

public class WebServicePost extends Activity implements OnClickListener {
	TextView tv;
	ProgressDialog progressDlg;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.webservice);
		findViewById(R.id.reqbtn).setOnClickListener(this);
		tv = (TextView) findViewById(R.id.result);
	}

	public void onClick(View v) {
		String str = "http://www.kma.go.kr/wid/queryDFSRSS.jsp";
		new HttpRequestTask().execute(str);
	}

	private class HttpRequestTask extends AsyncTask<String, Void, String> {
		protected void onPreExecute() {
			progressDlg = ProgressDialog.show(WebServicePost.this, "Wait",
					"Downloading...");
		}

		protected String doInBackground(String... strs) {
			StringBuffer sb = new StringBuffer();
			try {
				HttpClient client = new DefaultHttpClient();
				HttpPost post = new HttpPost(strs[0]);
				List<NameValuePair> params = new ArrayList<NameValuePair>();
				params.add(new BasicNameValuePair("zone", "2726067000"));
				UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params);
				post.setEntity(ent);
				HttpResponse responsePost = client.execute(post);
				HttpEntity resEntity = responsePost.getEntity();
				if (resEntity != null) {
					sb.append(EntityUtils.toString(resEntity));
				}
			} catch (MalformedURLException e) {
			} catch (UnsupportedEncodingException e) {
			} catch (ClientProtocolException e) {
			} catch (IOException e) {
			}
			return sb.toString();
		}

		protected void onPostExecute(String result) {
			progressDlg.dismiss();
			tv.setText(result);

		}// end of class HttpRequestTask
	}
}// end of class WebServicePost
